package app.sceledroid.activity;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences.Editor;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import app.sceledroid.R;
import app.sceledroid.entity.User;
import app.sceledroid.exception.CookieFetcherException;
import app.sceledroid.network.TestAsyncTask;
import app.sceledroid.services.SceleService;
import app.sceledroid.services.SimpleCrypto;
import app.sceledroid.services.SceleService.SceleBinder;



public class LoginActivity extends Activity {
	/** Called when the activity is first created. */
	
	public enum LoginStatus {
		SUCCED, ERROR, NOTYET
		
	}
	
	private SceleService sceleService;
	private boolean isBounded;
	private AlertDialog alertDialog; 
	private ProgressDialog progressDialog;
	private ConnectivityManager cm ; 
	private TelephonyManager tm;
	private ServiceConnection sceleServiceConnection = new ServiceConnection() {

		//@Override
		public void onServiceConnected(ComponentName componentName,
				IBinder iBinder) {
			// TODO Auto-generated method stub
			SceleBinder binder = (SceleBinder) iBinder;
			sceleService = binder.getService();
			isBounded = true;
			
		}

		//@Override
		public void onServiceDisconnected(ComponentName componentName) {
			// TODO Auto-generated method stub
			isBounded = false;
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		Intent service = new Intent(this, SceleService.class);
		startService(service);
		final EditText userText = (EditText) findViewById(R.id.usernameTextEdit);
		final EditText passwordText = (EditText) findViewById(R.id.passwordTextEdit);
		
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		final Editor e = pref.edit();//this.getPreferences(Context.MODE_PRIVATE).edit();
		final boolean fromPref;
		String username = pref.getString("username", "");
		String passwd = pref.getString("password", "");
		
		if((!username.equals("") && !passwd.equals("")) && (!username.equals("-") && !passwd.equals("-")) )
		{
			fromPref=true;
			userText.setText(username);
			String temp="";
			try {
				temp = SimpleCrypto.decrypt("SceleDroid", passwd);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
			passwordText.setText(temp);
		}
		else
		{
			fromPref=false;
		}
		cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		Button loginButton = (Button) findViewById(R.id.loginButton);

		alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
		
		
		alertDialog.setOnCancelListener(new OnCancelListener() {

			//@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				dialog.dismiss();

			}
		});
		loginButton.setOnClickListener(new OnClickListener() {

			//@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				tm.getDataActivity();
				cm.getActiveNetworkInfo();
				if( tm.getDataActivity() != TelephonyManager.DATA_ACTIVITY_DORMANT && !cm.getActiveNetworkInfo().isFailover() && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isAvailable())
				{
					
					if (sceleService != null) {
						try {
							if(sceleService.isCookieAlreadyInJar())
							sceleService.getDefaultCookies(LoginActivity.this);
							String username = userText.getText().toString();
							String password = passwordText.getText().toString();
							
							if(!fromPref){
								e.putString("username", userText.getText().toString());
								e.commit();
								String temp="";
								try {
									temp = SimpleCrypto.encrypt("SceleDroid", passwordText.getText().toString());
								} catch (Exception e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								e.putString("password", temp);
								e.commit();
							}
							
							if(!username.equals("") && !password.equals(""))
							{

								progressDialog = ProgressDialog.show(LoginActivity.this, "Requesting", "Login", true, false);
								
								LoginStatus stat = LoginStatus.NOTYET;
								sceleService.authenticateAs(LoginActivity.this, username, password, stat, progressDialog);
								
							}
							else
								showDialog("Error Login Failed", "Please fill the form first!");
						} catch (CookieFetcherException e) {
							// TODO Auto-generated catch block
							Toast.makeText(LoginActivity.this, e.getMessage(),
									Toast.LENGTH_LONG).show();
						}
					} else {
						bindToService();
					}
				}
			}
		});


	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		bindToService();

	}

	private void showDialog(String title, String message) {
		alertDialog.setTitle(title);
		alertDialog.setMessage(message);
		alertDialog.show();

	}

	private void bindToService() {
		Intent service = new Intent(this, SceleService.class);
		bindService(service, sceleServiceConnection, Context.BIND_AUTO_CREATE);

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (isBounded) {
			unbindService(sceleServiceConnection);
			isBounded = false;
		}
	}
	
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//intent for settings
		Intent intent = null ;
		//toast for others
		Context context = getApplicationContext();
		CharSequence help = "Help not implemented yet!";
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, help, duration);		
		
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.help:
	       // showHelp();
	    	showDialog("Info", "Not implemented yet!");
	        return true;
	    case R.id.settings:
	    	//settings here
	    	intent = new Intent(this, SettingsActivity.class);
	    	startActivity(intent);
	    	return true;
	    case R.id.credits:
	    	//credits her
	    	showDialog("Info", "Not implemented yet!");
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
}